package cn.com.nroad.web;

import cn.com.nroad.domain.Evidence;
import cn.com.nroad.service.EvidenceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@RestController
@Slf4j
public class EvidenceController {

    @Autowired
    private EvidenceService evidenceService;

    @Value("${file.upload-path}")
    private String path;

    @PostMapping("/upload")
    public Evidence upload(@RequestParam(name = "file")MultipartFile multipartFile){

        log.info("上传佐证材料{}",multipartFile.getOriginalFilename());
        Evidence evidence = new Evidence();
        if (!multipartFile.isEmpty()){
            String name = multipartFile.getOriginalFilename();
            String endFileName = name.substring(name.lastIndexOf("."));
            String targetFileName = UUID.randomUUID().toString() + endFileName;
            String timeStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String uriPath = timeStr.concat("/").concat(targetFileName);
            log.info("目标文件名{}",targetFileName);
            try {
                File parentFile = new File(path + timeStr);
                if (!parentFile.exists()){
                    parentFile.mkdirs();
                    parentFile.setWritable(true);
                }
                File tagetFile = new File(path.concat(uriPath));
                multipartFile.transferTo(tagetFile);
                log.info("上传文件成功,文件路径{}",tagetFile.getPath());
                evidence = evidenceService.upload(name, uriPath,tagetFile.length());
            } catch (Exception e) {
                log.error("上传文件异常",e);
            }
        }else {
            log.error("佐证材料为空");
            return null;
        }
       return evidence;
    }

    @GetMapping("/evidence/{id:.+}")
    public Evidence getEvidenceInfo(@PathVariable(name = "id") String id){
        Assert.hasText(id,"id is null");
        return evidenceService.getEvidenceById(id);
    }

    @GetMapping("/evidence/{id:.+}/download")
    public ResponseEntity<Resource> downloadEvidence(@PathVariable(name = "id") String id){

        Resource file = evidenceService.download(id);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\"" + evidenceService.getEvidenceById(id).getName() + "\"").body(file);
    }

    @DeleteMapping("/evidence/{id:.+}/delete")
    public void deleteEvidence(@PathVariable(name= "id") String id){

        evidenceService.deleteEvidence(id);
    }
}
